package com.tanhua.dubbo.api;

import com.tanhua.domain.mongo.*;
import com.tanhua.domain.vo.PageResult;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.ArrayList;
import java.util.List;

@Service
public class UserLikeApiImpl implements UserLikeApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public UserLikeCount findUserLikeCounts(Long userId) {
        //1. 统计互相喜欢数量
        UserLikeCount userLikeCount = new UserLikeCount();
        userLikeCount.setEachLoveCount(eachLoveCount(userId).intValue());
        userLikeCount.setLoveCount(loveCount(userId).intValue());
        userLikeCount.setFanCount(fanCount(userId).intValue());
        return userLikeCount;
    }

    @Override
    public PageResult findUserLikeList(Integer page, Integer pagesize, Integer type, Long userId) {
        switch (type) {
            case 1:
                return eachLoveList(page, pagesize, userId);
            case 2:
                return loveList(page, pagesize, userId);
            case 3:
                return fanList(page, pagesize, userId);
            case 4:
                return visitorList(page, pagesize, userId);
            default:
                return null;
        }
    }

    @Override
    public void removeFan(Long userId, Long targetUserId) {
        Query query = Query.query(Criteria.where("userId").is(targetUserId).and("likeUserId").is(userId));
        mongoTemplate.remove(query, UserLike.class);
    }

    @Override
    public void removeContact(Long userId, Long targetUserId, Integer type) {
        switch (type) {
            case 1:
                //删除好友关系,双向删除
                remove(userId, targetUserId);
                remove(targetUserId, userId);
            case 2:
                //TODO //用户userId 取消 对targetUserId 的喜欢
        }
    }

    //互相喜欢
    private Long eachLoveCount(Long userId) {
        Query query = Query.query(Criteria.where("userId").is(userId));
        return mongoTemplate.count(query, Friend.class);
    }

    //喜欢
    private Long loveCount(Long userId) {
        Query query = Query.query(Criteria.where("userId").is(userId));
        return mongoTemplate.count(query, UserLike.class);
    }

    //粉丝
    private Long fanCount(Long userId) {
        Query query = Query.query(Criteria.where("likeUserId").is(userId));
        return mongoTemplate.count(query, UserLike.class);
    }

    //互相喜欢翻页列表
    private PageResult eachLoveList(Integer page, Integer pagesize, Long userId) {
        Query query = Query.query(Criteria.where("userId").is(userId));
        query.with(Sort.by(Sort.Order.desc("created")));
        query.with(PageRequest.of(page - 1, pagesize));
        List<Friend> userLikeList = mongoTemplate.find(query, Friend.class);
        long count = mongoTemplate.count(query, Friend.class);

        List<CommonLikeUser> commonLikeUserList = new ArrayList<>();
        for (Friend friend : userLikeList) {
            CommonLikeUser user = new CommonLikeUser();
            user.setTargetUserId(friend.getFriendId());
            user.setScore(score(userId, user.getTargetUserId()));
             commonLikeUserList.add(user);
        }
        int pages = (int) Math.ceil(count * 1.0 / pagesize);
        return new PageResult((int) count, pagesize, pages, page, commonLikeUserList);
    }

    //喜欢
    private PageResult loveList(Integer page, Integer pagesize, Long userId) {
        Query query = Query.query(Criteria.where("userId").is(userId));
        query.with(Sort.by(Sort.Order.desc("created")));
        query.with(PageRequest.of(page - 1, pagesize));
        List<UserLike> userLikeList = mongoTemplate.find(query, UserLike.class);
        long count = mongoTemplate.count(query, UserLike.class);

        List<CommonLikeUser> commonLikeUserList = new ArrayList<>();
        for (UserLike userLike : userLikeList) {
            CommonLikeUser user = new CommonLikeUser();
            user.setTargetUserId(userLike.getLikeUserId());
            user.setScore(score(userId, user.getTargetUserId()));
            commonLikeUserList.add(user);
        }
        int pages = (int) Math.ceil(count * 1.0 / pagesize);
        return new PageResult((int) count, pagesize, pages, page, commonLikeUserList);
    }

    //粉丝
    private PageResult fanList(Integer page, Integer pagesize, Long userId) {
        Query query = Query.query(Criteria.where("likeUserId").is(userId));
        query.with(Sort.by(Sort.Order.desc("created")));
        query.with(PageRequest.of(page - 1, pagesize));
        List<UserLike> userLikeList = mongoTemplate.find(query, UserLike.class);
        long count = mongoTemplate.count(query, UserLike.class);

        List<CommonLikeUser> commonLikeUserList = new ArrayList<>();
        for (UserLike userLike : userLikeList) {
            CommonLikeUser user = new CommonLikeUser();
            user.setTargetUserId(userLike.getUserId());
            user.setScore(score(userId, user.getTargetUserId()));
            commonLikeUserList.add(user);
        }
        int pages = (int) Math.ceil(count * 1.0 / pagesize);
        return new PageResult((int) count, pagesize, pages, page, commonLikeUserList);
    }

    //最近访客
    private PageResult visitorList(Integer page, Integer pagesize, Long userId) {
        Query query = Query.query(Criteria.where("userId").is(userId));
        query.with(Sort.by(Sort.Order.desc("created")));
        query.with(PageRequest.of(page - 1, pagesize));
        List<Visitor> visitorList = mongoTemplate.find(query, Visitor.class);
        long count = mongoTemplate.count(query, Visitor.class);

        List<CommonLikeUser> commonLikeUserList = new ArrayList<>();
        for (Visitor visitor : visitorList) {
            CommonLikeUser user = new CommonLikeUser();
            user.setTargetUserId(visitor.getVisitorUserId());
            user.setScore(score(userId, user.getTargetUserId()));
            commonLikeUserList.add(user);
        }
        int pages = (int) Math.ceil(count * 1.0 / pagesize);
        return new PageResult((int) count, pagesize, pages, page, commonLikeUserList);
    }


    //查询userId 和 targetUserId 的缘分值
    private Double score(Long userId, Long targetUserId) {
        //将targetUserId 推荐给 userId
        Query query = Query.query(Criteria.where("toUserId").is(userId).and("userId").is(targetUserId));
        RecommendUser recommendUser = mongoTemplate.findOne(query, RecommendUser.class);
        return recommendUser != null ? recommendUser.getScore() : 95D;
    }

    /*右滑喜欢 查询对方是否喜欢自己*/
    @Override
    public UserLike findId(Long id, Long userId) {
        Query query = new Query();
        query.addCriteria(Criteria.where("likeUserId").is(userId).and("userId").is(id));
        return mongoTemplate.findOne(query, UserLike.class);
    }

    /*添加当前用户喜欢对方的数据*/
    @Override
    public void insrt(UserLike userLike) {
        mongoTemplate.insert(userLike);
    }

    /*删除单项数据表 */
    @Override
    public void remove(Long id, Long userId) {
        Query query = new Query();
        query.addCriteria(Criteria.where("likeUserId").is(id).and("userId").is(userId));
        mongoTemplate.remove(query, UserLike.class);
    }

    @Override
    public UserLike quer(Long id, Long userId) {
        Query query = new Query();
        query.addCriteria(Criteria.where("likeUserId").is(userId).and("userId").is(id));
        return mongoTemplate.findOne(query, UserLike.class);
    }


    @Override
    public void removeId(Long id, Long userId) {
        Query query = new Query();
        query.addCriteria(Criteria.where("likeUserId").is(userId).and("userId").is(id));
        mongoTemplate.remove(query, UserLike.class);
    }

    /**
     * 给用户和卡牌用户添加喜欢
     *
     * @param userId
     * @param cardUserId
     */
    @Override
    public void loveCard(Long userId, Long cardUserId) {
        //判断卡片用户是否喜欢当前用户
        Query query = Query.query(Criteria.where("userId").is(cardUserId).and("likeUserId").is(userId));
        boolean exists = mongoTemplate.exists(query, UserLike.class);
        if (exists) {
            //如果存在，删除单向喜欢，添加好友关系
            UserLike userLike = mongoTemplate.findOne(query, UserLike.class);
            mongoTemplate.remove(userLike);
            Friend friend = new Friend();
            friend.setUserId(userId);
            friend.setFriendId(cardUserId);
            friend.setCreated(System.currentTimeMillis());
            mongoTemplate.insert(friend);
            friend = new Friend();
            friend.setUserId(cardUserId);
            friend.setFriendId(userId);
            friend.setCreated(System.currentTimeMillis());
            mongoTemplate.insert(friend);
        } else {
            //如果不存在，新增单向的喜欢关系
            UserLike userLike = new UserLike();
            userLike.setUserId(userId);
            userLike.setLikeUserId(cardUserId);
            userLike.setCreated(System.currentTimeMillis());
            mongoTemplate.insert(userLike);
        }
    }

    /**
     * 获取当前用户的粉丝的id数组
     *
     * @param userId
     * @return
     */
    @Override
    public List<Long> getFanIds(Long userId) {
        Query query = new Query();
        query.addCriteria(Criteria.where("likeUserId").is(userId));
        query.with(Sort.by(Sort.Order.desc("created")));
        List<UserLike> userLikeList = mongoTemplate.find(query, UserLike.class);
        List<Long> fansIds = new ArrayList<>();
        for (UserLike userLike : userLikeList) {
            fansIds.add(userLike.getUserId());
        }
        return fansIds;
    }

    /**
     * 获取当前用户单向喜欢的人的id的集合
     *
     * @param userId
     * @return
     */
    @Override
    public List<Long> getLikeIds(Long userId) {
        Query query = new Query();
        query.addCriteria(Criteria.where("userId").is(userId));
        List<UserLike> userLikeList = mongoTemplate.find(query, UserLike.class);
        if (userLikeList == null || userLikeList.size() == 0) {
            return null;
        }
        List<Long> likeIdList = new ArrayList<>();
        for (UserLike userLike : userLikeList) {
            likeIdList.add(userLike.getLikeUserId());
        }
        return likeIdList;
    }
}
